import os
import argparse

from enum import Enum, auto

__version__ = "0.2.1"


class AnalysisOption(Enum):
    SNP_FREQUENCY_RANK = auto()
    SNP_PHENOTYPE_PAIR_RANK = auto()
    SNP_ETHNICITY_PAIR_RANK = auto()
    SNP_PHENOTYPE_DUPLICATION_RANK = auto()
    PHENOTYPE_FREQUENCY_RANK = auto()
    PHENOTYPE_SNP_PAIR_RANK = auto()
    PHENOTYPE_ETHNICITY_PAIR_RANK = auto()
    ALL = auto()
    pass


# class OutputForm(Enum):
#     CHART = auto()
#     SHEET = auto()


def parser_check(parser: argparse.ArgumentParser):
    args = parser.parse_args()
    # check input files
    for file in args.input:
        if not os.path.isfile(file):
            parser.error(f"{file} is not a valid file!")


def get_parser():
    parser = argparse.ArgumentParser(
        prog="result_analysis",
        description='Analysis tool for results generated by GWAS_automatic_analysis')

    _ = parser.add_argument(
        "--input", "-i",
        required=True,
        nargs='+',
        help='List of input files'
    )

    _ = parser.add_argument(
        "--phenotype-reference", "--reference",
        type=str,
        required=True,
        help="Path to the phenotype reference file, which tells what the phenotype codings refers to."
    )

    _ = parser.add_argument(
        "--output", "-o",
        type=str,
        default="results",
        help="Output path"
    )

    _ = parser.add_argument(
        "--analysis", "-a",
        choices=[option.name for option in AnalysisOption],
        type=lambda x: arg_2_enum_name(AnalysisOption, x, parser),
        nargs="+",
        default=[AnalysisOption.ALL.name],
        help='Analysis option'
    )

    _ = parser.add_argument(
        "--version", "-V",
        action="version",
        version=f"%(prog)s {__version__}"
    )

    parser_check(parser)

    return parser


def arg_2_enum_name(T: type[Enum], input_str: str, parser: argparse.ArgumentParser):
    try:
        # 返回枚举成员
        return T[input_str.upper()].name
    except KeyError:
        parser.error(
            f"{input_str.upper()} is not an attribute of {T.__name__}!")
